package com.tang.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tang.constants.SystemConstants;
import com.tang.enums.AppHttpCodeEnum;
import com.tang.exception.SystemException;
import com.tang.sys.ResponseResult;
import com.tang.sys.entity.Comment;
import com.tang.sys.entity.User;
import com.tang.sys.mapper.CommentMapper;
import com.tang.sys.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.sys.service.IUserService;
import com.tang.sys.vo.CommentVo;
import com.tang.sys.vo.PageVo;
import com.tang.utils.BeanCopyUtils;
import com.tang.utils.JwtUtil;
import com.tang.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author shankaka
 * @since 2023-04-14
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Autowired
    private IUserService iUserService;

    //回复评论
    @Override
    public ResponseResult commentList(String commentType, Long articleId, Integer pageNum, Integer pageSize) {
        //查询对应文章的根评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();

        //对articleId进行判断
        queryWrapper.eq(SystemConstants.ARTICLE_COMMENT.equals(commentType),Comment::getArticleId,articleId);
        //根评论rootid为-1
        queryWrapper.eq(Comment::getRootId, SystemConstants.COMMENT_ROOTID_YES);

        //评论类型
        queryWrapper.eq(Comment::getType,commentType);
        queryWrapper.orderByDesc(Comment::getCreateTime);

        //分页查询
        Page<Comment> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);

        List<CommentVo> commentVoList = toCommentVoList((page.getRecords()));
        //查询所有根评论对应的子评论的集合 并且赋值给对应的属性
        for (CommentVo commentVo : commentVoList) {
            //先去查询对应的子评论
            List<CommentVo> children = getChildren(commentVo.getId());
            //赋值
            commentVo.setChildren(children);
        }

        return ResponseResult.okResult(new PageVo(commentVoList,page.getTotal()));
    }
    //回复评论
    @Override
    public ResponseResult addComment(Comment comment) {

        //评论内容不能为空
        if(!StringUtils.hasText(comment.getContent())){
            throw new SystemException(AppHttpCodeEnum.CONTENT_NOT_NULL);
        }

        save(comment);
        return ResponseResult.okResult();
    }
    //删除评论id
    @Override
    public ResponseResult deleteCommentId(Long id) {
        Long userId = SecurityUtils.getUserId();

        // 查询评论信息
        Comment comment = this.baseMapper.selectById(id);
        if (comment != null) {
            // 检查当前登录用户是否为评论的创建者
            if (userId.equals(comment.getCreateBy())) {
                // 删除评论
                this.baseMapper.deleteById(id);
                return ResponseResult.okResult(200, "删除评论成功");
            } else {
                return ResponseResult.errorResult(403, "当前用户无权限删除该评论");
            }
        } else {
            return ResponseResult.errorResult(404, "评论不存在");
        }
    }

    //根评论的id
    //根据根评论的id查询所有对应的子评论的集合
    private List<CommentVo> getChildren(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getRootId,id);
        List<Comment> comments = list(queryWrapper);
        List<CommentVo> commentVos = toCommentVoList(comments);

        // 递归查询子评论的子评论
        for (CommentVo commentVo : commentVos) {
            List<CommentVo> children = getChildren(commentVo.getId());
            commentVo.setChildren(children);
        }

        return commentVos;
    }

    private List<CommentVo> toCommentVoList(List<Comment> list){
        List<CommentVo> commentVos = BeanCopyUtils.copyBeanList(list,CommentVo.class);
        //遍历vo集合
        for (CommentVo commentVo : commentVos) {
            //通过creatyBy查询单个的用户名称并赋值
            User byId = iUserService.getById(commentVo.getCreateBy());
            if (byId == null){
                commentVo.setCreateBy(-1L);
            }
            String nickName = byId.getNickName();
            String avatar = byId.getAvatar();
            String userVip = byId.getUserVip();
            String userSvip = byId.getUserSvip();
            commentVo.setUsername(nickName);
            commentVo.setAvatar(avatar);
            commentVo.setUserVip(userVip);
            commentVo.setUserSvip(userSvip);

            //子评论
            if (commentVo.getToCommentUserId() != -1){
                User byIdChildren = iUserService.getById(commentVo.getToCommentUserId());
                String nickNameChildren = byIdChildren.getNickName();
                commentVo.setToCommentUserName(nickNameChildren);

            }

        }

        return commentVos;
    }
}
